"""
Case Type   : MOT
Case Name   : gs_dump/gs_restore备份恢复内存表数据(自定义归档格式)
Create At   : 2021/1/6
Owner       : opentestcase001
Description :
    1、修改配置文件增量检查点为off,重启数据库
    2、连接数据库，创建内存表，插入数据
    3、gs_dump导出(备份)内存表（自定义归档格式）
    4、gs_restore导入(恢复)内存表（自定义归档格式）
    5、清理环境
Expect      :
    1、修改成功，重启数据库成功
    2、连接数据库成功，创建内存表成功，插入数据成功
    3、导出数据成功
    4、导入数据成功
    5、清理环境成功
History     :
    modified by opentestcase010 at 2023/2/6，优化MOT用例
"""

import os
import unittest

from yat.test import macro
from yat.test import Node
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant


class MotDdlTest(unittest.TestCase):

    def setUp(self):
        self.logger = Logger()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.user_node = Node('PrimaryDbUser')
        self.constant = Constant()
        self.commonsh = CommonSH
        self.common = Common()
        self.config = 'enable_incremental_checkpoint'
        self.t_name = 't_mot_0104'
        self.logger.info(f'-----{os.path.basename(__file__)} start-----')
        self.logger.info('-----step1:修改配置，并重启数据库-----')
        show_msg = self.common.show_param(self.config)
        if 'off' not in show_msg:
            msg1 = self.primary_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'{self.config}=off')
            self.logger.info(msg1)
            msg2 = self.primary_sh.restart_db_cluster()
            self.logger.info(msg2)
            msg3 = self.primary_sh.get_db_cluster_status()
            self.assertTrue("Normal" or "Degrade" in msg3)
            show_msg = self.common.show_param(self.config)
            self.assertTrue('off' in show_msg)

    def test_mot_dump(self):
        text = '-----step2:创建MOT内存表，插入数据;expect:成功-----'
        self.logger.info(text)
        self.mot_path = os.path.join(macro.DB_INSTANCE_PATH, 'mot_test.dmp')
        sql_cmd = f'''drop foreign table if exists {self.t_name};
            create foreign table {self.t_name}(id int);
            insert into {self.t_name} values(generate_series(1,2000000));
            '''
        msg4 = self.primary_sh.execut_db_sql(sql_cmd)
        self.logger.info(msg4)
        self.assertIn(self.constant.CREATE_FOREIGN_SUCCESS_MSG, msg4)

        text = '-----step3:gs_dump以自定义归档格式导出内存表;expect:成功-----'
        self.logger.info(text)
        sql_cmd = f'''source {macro.DB_ENV_PATH};
            gs_dump {self.user_node.db_name} \
            -f {self.mot_path} \
            -t {self.t_name} \
            -p {self.user_node.db_port} \
            -F c
            '''
        msg5 = self.user_node.sh(sql_cmd).result()
        self.logger.info(msg5)
        self.assertIn('dump database {} successfully'.format(
            self.user_node.db_name), msg5.split('\n')[-2].strip())

        text = '-----step4:gs_restore导入自定义归档格式内存表;expect:成功-----'
        self.logger.info(text)
        sql_cmd = f'''source {macro.DB_ENV_PATH};
            gs_restore -d {self.user_node.db_name} \
            -p {self.user_node.db_port} \
            -c {self.mot_path}
            '''
        msg6 = self.user_node.sh(sql_cmd).result()
        self.logger.info(msg6)
        self.assertIn(self.constant.RESTORE_SUCCESS_MSG,
                      msg6.splitlines()[-2].strip())

        text = '-----step5:清理环境;expect:成功-----'
        self.logger.info(text)
        del_cmd = f'''source {macro.DB_ENV_PATH};
                    gsql {self.user_node.db_name} \
                    -p {self.user_node.db_port} \
                    -c "drop foreign table {self.t_name} cascade";
                    rm -rf {self.mot_path}
                    '''
        self.logger.info(del_cmd)
        del_res = self.user_node.sh(del_cmd).result()
        self.assertIn(self.constant.DROP_FOREIGN_SUCCESS_MSG, del_res)

    def tearDown(self):
        self.logger.info('-----this is tearDown-----')
        self.logger.info('-----恢复配置，enable_incremental_checkpoint=on-----')
        show_msg = self.common.show_param(self.config)
        if 'on' not in show_msg:
            msg7 = self.primary_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'{self.config}=on')
            self.logger.info(msg7)
            msg8 = self.primary_sh.restart_db_cluster()
            self.logger.info(msg8)
            msg9 = self.primary_sh.get_db_cluster_status()
            self.assertTrue("Normal" or "Degrade" in msg9)
        show_msg = self.common.show_param(self.config)
        self.assertTrue('on' in show_msg)
        self.logger.info(f'-----{os.path.basename(__file__)} end-----')
